<template>
  <div>
    <van-index-bar :index-list="computedCityList" @select="handSelect">
      <div v-for="data in cityList" :key="data.type">
        <van-index-anchor :index="data.type" />
        <van-cell :title="item.name" v-for="(item, index) in data.list" :key="index" @click="handleChangePage(item.name, item.cityId)"/>
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import { IndexBar, IndexAnchor, Cell, Toast } from 'vant'
import http from '@/util/http'
import { mapMutations } from 'vuex'

Vue.use(IndexBar)
Vue.use(IndexAnchor)
Vue.use(Cell)
export default {
  name: '',

  data () {
    return {
      cityList: []
    }
  },
  computed: {
    computedCityList () {
      return this.cityList.map(item => item.type)
    }
  },
  methods: {
    ...mapMutations('CityModule', ['changeCityName', 'changeCityId']),
    handleCityData (cities) {
      // console.log(cities)
      const letterArr = []
      const newCities = []
      for (let code = 65; code < 91; code++) {
        letterArr.push(String.fromCharCode(code))
      }
      letterArr.forEach((letter) => {
        const list = cities.filter(item => item.pinyin.substring(0, 1).toUpperCase() === letter)
        if (list.length > 0) {
          newCities.push({
            type: letter,
            list: list
          })
        }
      })
      return newCities
    },
    handSelect (index) {
      Toast(index)
    },
    handleChangePage (cityName, cityId) {
      // 记录cityid和cityname
      // this.$store.state.cityName = cityName
      // this.$store.commit('changeCityName', cityName)
      // this.$store.commit('changeCityId', cityId)
      this.changeCityName(cityName)
      this.changeCityId(cityId)
      this.$router.back()
    }
  },
  mounted () {
    http({
      url: '/gateway?k=1750515',
      headers: {
        'X-Host': 'mall.film-ticket.city.list'
      }
    }).then((res) => {
      this.cityList = this.handleCityData(res.data.data.cities)
    })
  }
}

</script>
<style scoped lang='less'>
</style>
